﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Utilities;
using Models.WebSite_HaiSheng;
using Telerik.Web.Mvc;
using System.IO;
namespace WebSite_HaiSheng.Controllers
{
    public class ImageController : Controller
    {
        public ViewResult Index()
        {
            return View(CH.GetAllData<Image>());
        }

         public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments)
         {             
             foreach (var file in attachments)
             {
                 var fileName = Path.GetFileName(file.FileName).Replace(" ","");
                 var physicalPath = Path.Combine(Server.MapPath("~/App_Data/Images"), fileName);        
                 // file.SaveAs(physicalPath);            
             }            
             // Return an empty string to signify success            
             return Content("");        
         }       
        public ActionResult Remove(string[] fileNames)        
        {            
            // The parameter of the Remove action must be called "fileNames"           
            foreach (var fullName in fileNames)            
            {                
                var fileName = Path.GetFileName(fullName);
                var physicalPath = Path.Combine(Server.MapPath("~/App_Data/Images"), fileName);                               
                // TODO: Verify user permissions                
                if (System.IO.File.Exists(physicalPath))                
                {                    
                    // The files are not actually removed in this demo                    
                    // System.IO.File.Delete(physicalPath);               
                }            
            }            
            // Return an empty string to signify success           
            return Content("");        
        }

        [GridAction]
        public ActionResult AjaxImageIndex(int RelateId, string RelateType)
        {
            var db = CH.DB;
            var images =  from ir in db.ImageRelateTos
                          from image in db.Images
                          where ir.RelateId == RelateId && image.ID == ir.ImageId && ir.RelateType == RelateType
                         select image;


            var data = new GridModel<Image>(images);
            return View(data);
        }

        public ViewResult Details(int id)
        {
            return View(CH.GetDataById<Image>(id));
        }
        public ActionResult Create(int RelateId, string RelateType)
        {
            ViewBag.RelateId = RelateId;
            ViewBag.RelateType = RelateType;
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(Image item, int relateid, string relatetype, IEnumerable<HttpPostedFileBase> attachments)
        {
            if (attachments==null || attachments.Count() == 0)
            {
                ModelState.AddModelError("", "未发现上传文件");
            }

            if (ModelState.IsValid)
            {
                foreach (var file in attachments)
                {
                    var fileName = Path.GetFileName(file.FileName).Replace(" ", "");
                    string serverpath = "/Uploads/Images/" + relatetype + "/" + relateid.ToString();
                    string path = Server.MapPath(serverpath);
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    var physicalPath = Path.Combine(path, fileName);
                    file.SaveAs(physicalPath);
                    item.ImageUrl = serverpath+ "/" + fileName;
                }
                
                CH.Create<Image>(item);
                CH.Create<ImageRelateTo>(new ImageRelateTo() { ImageId = item.ID, RelateId = relateid, RelateType = relatetype });
                if (!string.IsNullOrEmpty(relatetype))
                {
                    return RedirectToAction("Index", relatetype);
                }
                return RedirectToAction("Index");
            }
            else
            {
                ViewBag.RelateId = relateid;
                ViewBag.RelateType = relatetype;
            }
            return View(item);
        }

        public JsonResult GetImage(int id)
        {
            var img = CH.GetDataById<Image>(id);
            return Json(img,JsonRequestBehavior.AllowGet);
        }
        public ActionResult Edit(int id,string RelateType)
        {
            ViewBag.RelateType = RelateType;
            return View(CH.GetDataById<Image>(id));
        }

        [HttpPost]
        public ActionResult Edit(Image item, string relatetype, IEnumerable<HttpPostedFileBase> attachments)
        {
            if (ModelState.IsValid)
            {
                //删除旧文件

                if (attachments != null)
                {
                    foreach (var file in attachments)
                    {
                        var fileName = Path.GetFileName(file.FileName).Replace(" ", "");
                        item.ImageUrl = fileName;
                        var ri = CH.GetAllData<ImageRelateTo>().FirstOrDefault(i => i.ImageId == item.ID);
                        if (ri != null)
                        {
                            string serverpath = "/Uploads/Images/" + ri.RelateType + "/" + ri.RelateId.ToString();
                            string path = Server.MapPath(serverpath);
                            if (!Directory.Exists(path))
                            {
                                Directory.CreateDirectory(path);
                            }
                            var physicalPath = Path.Combine(path, fileName);
                            file.SaveAs(physicalPath);
                            item.ImageUrl = serverpath+"/" + fileName;
                        }
                        else
                        {
                            ModelState.AddModelError("", "Image 的关联表值为空");
                            return View(item);
                        }
                       
                    }
                }

                CH.Edit<Image>(item);
                if (!string.IsNullOrEmpty(relatetype))
                {
                    return RedirectToAction("Index", relatetype);
                }
                return RedirectToAction("Index");
            }
            return View(item);
        }

        public ActionResult Delete(int id, string RelateType)
        {
            ViewBag.RelateType = RelateType;
            return View(CH.GetDataById<Image>(id));
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id, string relatetype)
        {
            var relatedata = CH.GetAllData<ImageRelateTo>(i => i.ImageId == id && i.RelateType==relatetype).FirstOrDefault();
            if (relatedata != null)
                CH.Delete<ImageRelateTo>(relatedata.ID);

            CH.Delete<Image>(id);

            if (!string.IsNullOrEmpty(relatetype))
            {
                return RedirectToAction("Index", relatetype);
            }
            return RedirectToAction("Index");
        }
    }
}
